<template>
  <div class="front-header">
    <div class="bg-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
    </div>
    <div class="header-container">
      <div class="logo-area" @click="$router.push('/')">
        <img src="@/assets/imgs/logo.png" alt="百货商城" class="logo-img" />
      </div>
      <el-menu mode="horizontal" :router="true" :default-active="activePath" class="nav-menu">
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/products">全部商品</el-menu-item>
        <el-menu-item index="/cart">购物车</el-menu-item>
        <el-menu-item index="/order">我的订单</el-menu-item>
        <el-menu-item index="/articles">百货资讯</el-menu-item>
      </el-menu>
      <div class="right-section">
        <div class="search-box">
          <el-input
              v-model="searchKey"
              placeholder="搜索商品..."
              @keyup.enter.native="handleSearch"
              class="search-input"
              clearable
          >
            <i slot="prefix" class="el-icon-search"></i>
          </el-input>
        </div>
        <div class="user-actions">
          <template v-if="!isLoggedIn">
            <el-button type="primary" class="login-btn" @click="goToLogin">
              <i class="el-icon-user"></i>
              <span>登录</span>
            </el-button>
          </template>
          <template v-else>
            <!-- 头像区域：有上传的头像显示图片，否则显示默认占位图标 -->
            <div class="avatar-container">
              <template v-if="userInfo.avatar">
                <img
                    :src="'/api' + userInfo.avatar"
                    class="header-avatar"
                    alt="用户头像"
                >
              </template>
              <template v-else>
                <!-- 模拟默认占位图标，用 Element Plus 图标实现类似效果，可根据需求替换样式 -->
                <div class="default-avatar">
                  <i class="el-icon-user" style="font-size: 24px; color: #fff;"></i>
                </div>
              </template>
            </div>
            <el-dropdown trigger="click">
              <div class="user-info">
                <span class="username">{{ userInfo.username }}</span>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="goToUserCenter">
                  <i class="el-icon-user"></i> 个人中心
                </el-dropdown-item>
                <el-dropdown-item @click.native="goToFavorite">
                  <i class="el-icon-star-off"></i> 我的收藏
                </el-dropdown-item>
                <!-- 如果是 MERCHANT 角色，显示商家仪表盘 -->
                <el-dropdown-item v-if="userInfo.role === 'MERCHANT'" @click.native="goToMerchantDashboard">
                  <i class="el-icon-data-analysis"></i> 商品后台
                </el-dropdown-item>
                <!-- 如果是 ADMIN 角色，显示管理页面 -->
                <el-dropdown-item v-if="userInfo.role === 'ADMIN'" @click.native="goToAdminPage">
                  <i class="el-icon-setting"></i> 管理后台
                </el-dropdown-item>
                <el-dropdown-item @click.native="logout">
                  <i class="el-icon-switch-button"></i> 退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import router from '@/router';

export default {
  name: 'FrontHeader',
  props: {
    // 接收从 UserCenter 传递过来的用户信息，用于更新头像等
    userInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      searchKey: '',
      isLoggedIn: false
    }
  },
  created() {
    this.checkLoginStatus();
  },
  watch: {
    // 监听 userInfo 变化，更新登录状态等
    userInfo(newVal) {
      if (newVal && Object.keys(newVal).length > 0) {
        this.isLoggedIn = true;
      } else {
        this.isLoggedIn = false;
      }
    }
  },
  methods: {
    checkLoginStatus() {
      const token = localStorage.getItem('token');
      const frontUserStr = localStorage.getItem('frontUser');
      const backUserStr = localStorage.getItem('backUser');

      if (token) {
        // 先检查 frontUser
        if (frontUserStr) {
          try {
            const frontUser = JSON.parse(frontUserStr);
            // 允许 USER、MERCHANT 和 ADMIN 角色登录
            if (['USER', 'MERCHANT', 'ADMIN'].includes(frontUser.role)) {
              this.isLoggedIn = true;
              this.userInfo = frontUser;
              return;
            }
          } catch (error) {
            this.logout();
          }
        }

        // 再检查 backUser
        if (backUserStr) {
          try {
            const backUser = JSON.parse(backUserStr);
            // 允许 MERCHANT 和 ADMIN 角色登录
            if (['MERCHANT', 'ADMIN'].includes(backUser.role)) {
              this.isLoggedIn = true;
              this.userInfo = backUser;
              return;
            }
          } catch (error) {
            this.logout();
          }
        }
      }

      this.isLoggedIn = false;
    },
    goToLogin() {
      this.$router.push('/login')
    },
    goToUserCenter() {
      this.$router.push('/user-center')
    },
    goToFavorite() {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      this.$router.push('/favorite')
    },
    goToMerchantDashboard() {
      this.$router.push('/merchantDashboard')
    },
    goToAdminPage() {
      this.$router.push('/showView')
    },
    logout() {
      localStorage.removeItem('token');
      localStorage.removeItem('frontUser');
      localStorage.removeItem('backUser');
      this.isLoggedIn = false;
      this.userInfo = {};
      this.$message.success('已退出登录');
      this.$router.push('/');
      window.location.reload()
    },
    handleSearch() {
      if (!this.searchKey.trim()) {
        this.$message({
          type: 'warning',
          message: '请输入搜索关键词'
        })
        return
      }
      this.$router.push({
        path: '/search',
        query: {
          keyword: this.searchKey.trim()
        }
      })
      this.searchKey = ''
    },
  },
  computed: {
    activePath() {
      return this.$router.currentRoute.fullPath;
    }
  }
}
</script>

<style scoped>
.front-header {
  position: sticky;
  top: 0;
  z-index: 1000;
  background: linear-gradient(135deg, #fffef5 0%, #fff8e5 100%);
  box-shadow: 0 2px 12px rgba(255, 170, 0, 0.07);
  min-height: 72px;
  overflow: visible;
}
.bg-decoration {
  position: absolute;
  top: 0; left: 0; width: 100%; height: 100%;
  z-index: 0;
  pointer-events: none;
}
.header-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 32px;
  height: 72px;
  display: flex;
  align-items: center;
  gap: 32px;
  position: relative;
  z-index: 1;
}
.logo-area {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 6px 16px;
  border-radius: 16px;
  background: linear-gradient(120deg, rgba(255,165,0,0.07) 0%, rgba(255,140,0,0.12) 100%);
  transition: box-shadow 0.3s, transform 0.3s;
  box-shadow: 0 2px 8px rgba(255,165,0,0.06);
}
.logo-area:hover {
  box-shadow: 0 4px 16px rgba(255,165,0,0.12);
  transform: translateY(-2px);
}
.logo-img {
  height: 38px;
  margin-right: 8px;
}
.nav-menu {
  border: none;
  background: transparent;
  height: 72px;
  line-height: 72px;
  flex: 1;
  z-index: 1;
}
:deep(.el-menu--horizontal > .el-menu-item) {
  height: 72px;
  line-height: 72px;
  padding: 0 22px;
  font-size: 17px;
  border-radius: 16px !important;
  margin: 0 2px;
  transition: background 0.3s, color 0.3s;
}
:deep(.el-menu--horizontal > .el-menu-item:hover) {
  background: linear-gradient(to right, #fff8e1, #fff3e0);
  color: #FF7F00;
}
:deep(.el-menu--horizontal > .el-menu-item.is-active) {
  color: #FF7F00;
  font-weight: 600;
  background: linear-gradient(to right, #ffe0b2, #ffecb3);
}
.right-section {
  display: flex;
  align-items: center;
  gap: 18px;
}
.search-box {
  width: 210px;
}
.search-input :deep(.el-input__inner) {
  height: 38px;
  line-height: 38px;
  border-radius: 19px;
  background: #f5f7fa;
  border: 1px solid #e0e0e0;
  padding-left: 38px;
  font-size: 14px;
  transition: all 0.3s;
}
.search-input :deep(.el-input__inner:focus) {
  background: #fff;
  border-color: #FF7F00;
  box-shadow: 0 0 0 2px rgba(255, 127, 0, 0.08);
}
.search-input :deep(.el-input__prefix) {
  left: 12px;
  display: flex;
  align-items: center;
  height: 100%;
}
.search-input :deep(.el-input__prefix i) {
  font-size: 16px;
  color: #FFA500;
}
.user-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}
.login-btn {
  border-radius: 16px;
  background: linear-gradient(90deg, #FF7F00, #FFA500);
  color: #fff;
  font-weight: 500;
  padding: 0 22px;
  height: 38px;
  font-size: 15px;
  box-shadow: 0 2px 8px rgba(255,127,0,0.08);
  border: none;
  transition: background 0.3s, box-shadow 0.3s;
}
.login-btn:hover {
  background: linear-gradient(90deg, #FF6600, #FF8C00);
  box-shadow: 0 4px 16px rgba(255,127,0,0.16);
}
.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 16px;
  border-radius: 16px;
  cursor: pointer;
  background: linear-gradient(120deg, #fff8e1 0%, #fff3e0 100%);
  color: #FF7F00;
  font-weight: 500;
  font-size: 15px;
  transition: box-shadow 0.3s;
}
.user-info:hover {
  box-shadow: 0 2px 8px rgba(255,127,0,0.10);
}
.username {
  font-size: 15px;
  color: #FF7F00;
}
:deep(.el-dropdown-menu) {
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(255,127,0,0.10);
  border: none;
  padding: 8px 0;
}
:deep(.el-dropdown-menu__item) {
  border-radius: 12px;
  font-size: 15px;
  padding: 10px 24px;
  color: #FF7F00;
  transition: background 0.3s, color 0.3s;
}
:deep(.el-dropdown-menu__item:hover) {
  background: #fff3e0;
  color: #FF6600;
}
/* 头像容器样式 */
.avatar-container {
  width: 36px;
  height: 36px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 上传后的头像样式 */
.header-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}
/* 默认占位图标容器样式（模拟你提供的黄色圆形效果） */
.default-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #ffc107; /* 黄色，可根据实际调整 */
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 992px) {
  .header-container {
    padding: 0 12px;
    gap: 12px;
  }
  .nav-menu {
    display: none;
  }
  .search-box {
    width: 120px;
  }
  .logo-img {
    height: 28px;
  }
}
@media (max-width: 576px) {
  .header-container {
    flex-direction: column;
    height: auto;
    gap: 8px;
    padding: 8px 4px;
  }
  .logo-area {
    padding: 4px 8px;
  }
  .search-box {
    width: 100px;
  }
}
</style>